package com.app.yc.ifapp;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.yc.ifapp.adapter.MyBaseAdapter;
import com.app.yc.ifapp.asynctask.WebApiRequest;
import com.app.yc.ifapp.entity.ApiResult;
import com.app.yc.ifapp.entity.School;
import com.app.yc.ifapp.utils.ApiUtils;
import com.app.yc.ifapp.utils.GZipUtils;
import com.app.yc.ifapp.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class SchoolActivity extends ListActivity implements AdapterView.OnItemClickListener {

    List<School> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school);

        //获取并缩放左箭头
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.back_arrow);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 3,
                drawable.getIntrinsicHeight() / 3);
        //获取到控件
        TextView back = (TextView) findViewById(R.id.school_back);
        //设置右箭头
        back.setCompoundDrawables(drawable, null, null, null);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        WebApiRequest request = new WebApiRequest();
        request.setAsyncTaskCallBack(new WebApiRequest.AsyncTaskCallBack() {

            @Override
            public void onTaskOver(String result) {

                if (TextUtils.isEmpty(result)) {
                    Toast.makeText(SchoolActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                            .show();
                    finish();
                    return;
                }

                list = getData(result);

                if (list == null || list.size() <= 0) {
                    Toast.makeText(SchoolActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                            .show();
                    finish();
                    return;
                }

                MyBaseAdapter<School> adapter = new MyBaseAdapter<>(SchoolActivity.this,
                        R.layout.item_school,
                        list,
                        new MyBaseAdapter.Callback<School>() {

                            @Override
                            public void onGetView(int i, View v, School obj) {

                                TextView tv = (TextView) v.findViewById(R.id.school_name);
                                ImageView iv = (ImageView) v.findViewById(R.id.school_img);
                                tv.setText(obj.getName());
                                iv.setTag(i);

                                try {
                                    byte[] buffer = GZipUtils.decompressForGzip(obj.getImage());
                                    if (buffer != null && buffer.length > 0) {
                                        Bitmap img = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
                                        if (img != null) {
                                            iv.setImageBitmap(img);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                setListAdapter(adapter);

                ((ListView) findViewById(android.R.id.list))
                        .setOnItemClickListener(SchoolActivity.this);
            }
        });

        try {
            request.execute(ApiUtils.API + ApiUtils.SCHOOLS, StringUtils.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(SchoolActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                    .show();
        }
    }

    private List<School> getData(String schools) {
        try {
            Gson gson = new Gson();
            ApiResult<List<School>> apiResult = gson.fromJson(schools,
                    new TypeToken<ApiResult<List<School>>>() {
                    }.getType());

            if (apiResult != null && apiResult.getResult()) {
                if (apiResult.getData() != null && apiResult.getData().size() > 0) {
                    list = apiResult.getData();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 响应ListView中item的点击事件
     */
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
        Intent intent = new Intent();
        intent.putExtra("school", list.get(position).getName());// 放入返回值
        intent.putExtra("url", list.get(position).getUrl());// 放入返回值
        setResult(0, intent);// 放入回传的值,并添加一个Code,方便区分返回的数据
        finish();// 结束当前的activity,等于点击返回按钮
    }
}
